
import urllib
import urllib.request


import demjson
import re

import Conn


def getCodeAndPrice(url):

    code=url.split("/")
    code=code[3].split(".")[0]
    price = doGetPrice(url)
    return code,price


def doGetPrice(url):
    if (url == None or len(url) == 0):
        return None
    code=url.split("/")
    code=code[3].split(".")[0]
    opener = urllib.request.build_opener()
    data = opener.open('https://p.3.cn/prices/get?skuid=J_' + code).read()
    data = data.decode('utf-8', 'ignore')
    json = demjson.decode(data)
    price = json[0]['p']
    return price


def downloadPicture(url,ID):
    opener = urllib.request.build_opener()
    data = opener.open(url).read()
    data = data.decode("GBK",'ignore')

    res_tr=r'//img(.*?)/n1/(.*?).jpg'
    match = re.search(res_tr, data, 0)
    pictureUrl="https:"+data[match.start():match.end()]


    urllib.request.urlretrieve(pictureUrl,Conn.getPictureLoc()+str(ID)+".jpg")




